<?php
/**
 * Created by PhpStorm.
 * User: ruma
 * Date: 2019/1/27
 * Time: 9:55
 */

namespace app\admin\model;


use app\admin\validate\ArticleAddValidate;
use app\common\model\AdminBaseModel;

class Article extends AdminBaseModel
{
    protected $pk = 'arc_id';
    protected $table = 'article';
    protected $auto = ['admin_id'];
    protected $insert = ['sendtime'];
    protected $update = ['update_time'];

    public function setAdminIdAttr() {
        return session('admin_id');
    }
    public function setSendtimeAttr() {
        return time();
    }
    public function setUpdateTimeAttr() {
        return time();
    }


    //模型关联
    public function category(){
        return $this->belongsTo('Category','cate_id','cate_id');
    }


    //获取文章列表信息
    public function getAllArticle(){
        $article = $this->where('is_recycle','=',2)->with('category')->paginate(8);
        return $article;
    }

    //获取回收站列表信息
    public function getRecycleArticle(){
        $recycle = $this->where('is_recycle','=',1)->with('category')->paginate(2);
//        halt($recycle);
        return $recycle;
    }


    //添加文章到数据库
    public function addArticleData(){
        $postData = (new ArticleAddValidate())->postCheckAndGet();

        //添加文章数据
        $this->allowField(true)->save($postData);

        //添加文章标签关联表数据
        foreach($postData['tid'] as $value){
            $arcTagData = [
                'arc_id' => $this->arc_id,
                'tid' => $value
            ];
        }
        (new ArcTag())->save($arcTagData);

        return true;
    }
    //编辑文章
    public function editArticleData(){
        $postData = (new ArticleAddValidate())->postCheckAndGet();
        $arc_id = $postData['arc_id'];
        //更新数据
        $this->where('arc_id','=',$arc_id)
             ->update([
                 'arc_title' => $postData['arc_title'],
                 'arc_author' => $postData['arc_author'],
                 'cate_id' => $postData['cate_id'],
                 //留个图片
                 'arc_keyword' => $postData['arc_keyword'],
                 'arc_content' => $postData['arc_content']
             ]);

        //删除并更新tag(关联模型数据)
        $arc_tag = new ArcTag();
        $result = $arc_tag->where('arc_id','=',$arc_id)->select();
        //如果存在则删除不存在直接执行添加
        if ($result){
            $arc_tag->where('arc_id','=',$arc_id)->delete();
        }
        foreach($postData['tid'] as $value){
            $arcTagData = [
                'arc_id' => $arc_id,
                'tid' => $value
            ];
            $arc_tag->create($arcTagData);
        }
        return true;
    }

    //获取编辑的文章信息
    public function getArticleDataById($arc_id){
        $Art_data = $this->find($arc_id)->toArray();
        return $Art_data;
    }


}